import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'
import { DetailBaseClass } from '@shared/classes/DetailBaseClass'
import { RiskControlRule, RiskRuleModeMap, LevelOptions } from '@shared/interfaces/risk-control'
import { ActivatedRoute } from '@angular/router'
import { NzMessageService } from 'ng-zorro-antd'
import { PageService } from '@shared/services/page.service'
import { RiskService } from '../../risk.service'
import { DataService } from '@shared/services/data.service'
import { deepCopy } from '@delon/util'
import { IBaseInfoColumn } from '@shared/interfaces/baseInfo'
import { Validators } from 'app/utils/validator'
import { riskControlRuleNameLength, riskControlRuleMin, riskControlRuleMax, riskControlRuleQuotaReg  } from 'app/utils/contraints'
import { LevelMap } from '@shared/interfaces/common'
import { DetailHeaderComponent } from '@shared/components/detail-header/detail-header.component'
import { I18NService } from '@core'

@Component({
  selector: 'app-risk-rule-detail',
  templateUrl: './detail.component.html',
})
export class RiskRuleDetailComponent extends DetailBaseClass<RiskControlRule> implements OnInit {
  @ViewChild('tpCurrency') tpCurrency: TemplateRef<void>
  @ViewChild('tpLevel') tpLevel: TemplateRef<void>
  @ViewChild(DetailHeaderComponent) detailHeaderComponent: DetailHeaderComponent
  singleTradeColumns: IBaseInfoColumn[] = []
  singleDayOrMonColumns: IBaseInfoColumn[] = []
  refundColumns: IBaseInfoColumn[] = []
  levelOptions = LevelOptions

  type: string

  constructor(
    public route: ActivatedRoute,
    public msg: NzMessageService,
    public pageService: PageService,
    private riskService: RiskService,
    private dataService: DataService,
    private i18n: I18NService,
  ) {
    super(pageService)
  }

  ngOnInit() {
    this.id = this.route.snapshot.params['ruleId']
    this.type = this.route.snapshot.params['type']

    this.request()
  }

  init(): void {
    this.singleTradeColumns = [
      {
        span: 6,
        index: 'name',
        label: '规则名称',
        labelI18n: 'RISK_CTRL.RULE.NAME',
        validator: {
          funcs: [Validators.required, Validators.maxLength(riskControlRuleNameLength)],
          errorTips: [
            this.trans('VALIDATION.REQUIRED', { name: this.trans('RISK_CTRL.RULE.NAME') }),
            this.trans('VALIDATION.MAX_LENGTH', { length: riskControlRuleNameLength }),
          ],
        },
      },
      {
        span: 6,
        index: 'mode',
        label: '规则模式',
        labelI18n: 'RISK_CTRL.RULE.MODE',
        disEditable: true,
        displayValue: this.trans(RiskRuleModeMap[this.detailData.mode]),
      },
      {
        span: 4,
        index: 'quota',
        label: '额度-动态码',
        labelI18n: 'GENERAL.INFO.QUOTA.DYNAMIC_CODE',
        validator: {
          funcs: [
            Validators.required,
            Validators.pattern(riskControlRuleQuotaReg),
            Validators.min(riskControlRuleMin),
            Validators.max(riskControlRuleMax),
          ],
          errorTips: [
            this.trans('VALIDATION.REQUIRED', { name: this.trans('GENERAL.INFO.QUOTA.DYNAMIC_CODE') }),
            this.trans('VALIDATION.PATTERN.INTEGER_ONLY'),
            this.trans('VALIDATION.MIN_VALUE', { value: riskControlRuleMin }),
            this.trans('VALIDATION.MAX_VALUE', { value: riskControlRuleMax }),
          ],
        },
      },
      {
        span: 4,
        index: 'quotaStatic',
        label: '额度-静态码',
        labelI18n: 'GENERAL.INFO.QUOTA.STATIC_CODE',
        validator: {
          funcs: [
            Validators.required,
            Validators.pattern(riskControlRuleQuotaReg),
            Validators.min(riskControlRuleMin),
            Validators.max(riskControlRuleMax),
          ],
          errorTips: [
            this.trans('VALIDATION.REQUIRED', { name: this.trans('GENERAL.INFO.QUOTA.STATIC_CODE') }),
            this.trans('VALIDATION.PATTERN.INTEGER_ONLY'),
            this.trans('VALIDATION.MIN_VALUE', { value: riskControlRuleMin }),
            this.trans('VALIDATION.MAX_VALUE', { value: riskControlRuleMax }),
          ],
        },
      },
      {
        span: 4,
        index: 'currency',
        label: '币种',
        labelI18n: 'GENERAL.INFO.TRANSACTION_CURRENCY',
        template: this.tpCurrency,
      },
    ]

    this.singleDayOrMonColumns = [
      {
        span: 6,
        index: 'name',
        label: '规则名称',
        labelI18n: 'RISK_CTRL.RULE.NAME',
        validator: {
          funcs: [Validators.required, Validators.maxLength(riskControlRuleNameLength)],
          errorTips: [
            this.trans('VALIDATION.REQUIRED', { name: this.trans('RISK_CTRL.RULE.NAME') }),
            this.trans('VALIDATION.MAX_LENGTH', { length: riskControlRuleNameLength }),
          ],
        },
      },
      {
        span: 6,
        index: 'mode',
        label: '规则模式',
        labelI18n: 'RISK_CTRL.RULE.MODE',
        disEditable: true,
        displayValue: RiskRuleModeMap[this.detailData.mode],
      },
      {
        span: 6,
        index: 'quota',
        label: '额度',
        labelI18n: 'GENERAL.INFO.QUOTA',
        validator: {
          funcs: [
            Validators.required,
            Validators.pattern(riskControlRuleQuotaReg),
            Validators.min(riskControlRuleMin),
            Validators.max(riskControlRuleMax),
          ],
          errorTips: [
            this.trans('VALIDATION.REQUIRED', { name: this.trans('GENERAL.INFO.QUOTA') }),
            this.trans('VALIDATION.PATTERN.INTEGER_ONLY'),
            this.trans('VALIDATION.MIN_VALUE', { value: riskControlRuleMin }),
            this.trans('VALIDATION.MAX_VALUE', { value: riskControlRuleMax }),
          ],
        },
      },
      {
        span: 6,
        index: 'currency',
        label: '币种',
        labelI18n: 'GENERAL.INFO.TRANSACTION_CURRENCY',
        template: this.tpCurrency,
      },
    ]

    this.refundColumns = [
      {
        span: 6,
        index: 'name',
        label: '规则名称',
        labelI18n: 'RISK_CTRL.RULE.NAME',
        validator: {
          funcs: [Validators.required, Validators.maxLength(riskControlRuleNameLength)],
          errorTips: [
            this.trans('VALIDATION.REQUIRED', { name: this.trans('RISK_CTRL.RULE.NAME') }),
            this.trans('VALIDATION.MAX_LENGTH', { length: riskControlRuleNameLength }),
          ],
        },
      },
      {
        span: 6,
        index: 'type',
        label: '规则模式',
        labelI18n: 'RISK_CTRL.RULE.MODE',
        disEditable: true,
        displayValue: RiskRuleModeMap[this.detailData.type],
      },
      {
        span: 6,
        index: 'level',
        label: '退货控制维度',
        labelI18n: 'RISK_CTRL.LEVEL_CTRL_OF_REFUND',
        displayValue: LevelMap[this.detailData.level],
        template: this.tpLevel,
      },
      {
        span: 6,
        index: 'currency',
        label: '币种',
        labelI18n: 'GENERAL.INFO.TRANSACTION_CURRENCY',
        template: this.tpCurrency,
      },
    ]
  }

  request(): void {
    this.loading = true
    this.riskService.getRuleOne(this.type, parseInt(this.id, 10)).subscribe((riskControlRule: RiskControlRule) => {
      this.renderRiskRule(riskControlRule)
      this.saveDataToDataStore(riskControlRule)
      this.init()
      this.initialColumns()
      this.initColumns()
      this.loading = false
    })
  }

  renderRiskRule(riskControlRule: RiskControlRule): void {
    this.detailData = riskControlRule
  }

  cancelBase(): void {
    this.pageService.triggerBaseEdit(false)
    const rule = this.dataService.riskControlRule
    this.renderRiskRule(rule)
    this.initialColumns()
    this.initColumns()
  }

  saveBase(): void {
    if (!this.checkEditValidation()) {
      this.msg.error(this.trans('GENERAL.NOTIFICATION.VALIDATION_FAIL'))
      return
    }
    this.detailHeaderComponent.hideButtons()
    this.pageService.triggerBaseEdit(false)
    this.updateColumns()
    const rule = this.detailData
    const { id } = rule
    rule.quota = typeof rule.quota === 'string' ? parseInt(rule.quota, 10) : rule.quota
    rule.quotaStatic = typeof rule.quotaStatic === 'string' && rule.quotaStatic ? parseInt(rule.quotaStatic, 10) : null
    if (!rule.quotaStatic) delete rule.quotaStatic
    this.riskService.updateRule(this.type, id, rule).subscribe(
      () => {
        this.msg.success(this.trans('GENERAL.NOTIFICATION.UPDATE_SUCCESS'))
        this.request()
      },
      () => {
        this.msg.error(this.trans('GENERAL.NOTIFICATION.UPDATE_FAIL'))
      },
    )
  }

  saveDataToDataStore(riskControlRule: RiskControlRule): void {
    this.dataService.setRiskControlRule(deepCopy(riskControlRule))
  }

  initialColumns(): void {
    this.secondColumns = [
      {
        span: 12,
        index: 'createdAt',
        label: 'GENERAL.INFO.CREATED_AT',
        labelI18n: 'GENERAL.INFO.CREATED_AT',
        type: 'date',
        disEditable: true,
      },
      {
        span: 12,
        index: 'updatedAt',
        label: 'GENERAL.INFO.UPDATED_AT',
        labelI18n: 'GENERAL.INFO.UPDATED_AT',
        type: 'date',
        disEditable: true,
      },
    ]
    if (this.detailData.type === 'refund') {
      this.firstColumns = this.refundColumns
      return
    }

    switch (this.detailData.mode) {
      case '00':
        this.firstColumns = this.singleTradeColumns
        break
      case '01':
      case '30':
        this.firstColumns = this.singleDayOrMonColumns
        break
    }
  }

  trans(str: string, params?: Object): string {
    return this.i18n.fanyi(str, params)
  }
}
